import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { map, shareReplay } from "rxjs/operators";
import { Observable } from "rxjs";

export interface Joke {
  id: number;
  joke: string;
  categories: Array<string>;
}

export interface JokeResponse {
  type: string;
  value: Array<Joke>;
}

const API_ENDPOINT = 'https://api.icndb.com/jokes/random/5?limitTo=[nerdy]'; // "https://api.github.com/users";
const CACHE_SIZE = 1;

@Injectable({
  providedIn: 'root'
})
export class JokeService {

  constructor(
    private http: HttpClient
  ) { }

  get jokes() {
    return;
  }

  // step 1, COLD Obserable.
  // https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html

  private responseJokes() {
    return this.http.get<JokeResponse>(API_ENDPOINT).pipe(
      map(response => response.value)
    )
  }

  // step 2, HOT Obserable
  private cache$: Observable<Array<Joke>>;
  get jokes_hot() {
    if (!this.cache$) {
      this.cache$ = this.responseJokes()
        .pipe(
          shareReplay(CACHE_SIZE)
        );
    }
    return this.cache$;
  }
}
